<template>
  <view class="user-profile">
    <view class="avatar-container" @tap="editAvatar">
      <image class="avatar" :src="user.avatar"></image>
    </view>
    <text class="change-avatar" @click="editAvatar">修改头像</text>
    <uni-list>
      <uni-list-item clickable showArrow title="用户昵称" :rightText="user.nickname" @click="editNickname"></uni-list-item>
      <uni-list-item clickable showArrow title="邮箱" :rightText="user.email" @click="editEmail"></uni-list-item>
    </uni-list>
    <button @tap="changePassword">修改密码</button>
    <button @tap="openDelPopup">注销账号</button>

    <!-- 编辑用户信息弹窗 -->
    <uni-popup ref="editpopup" type="dialog">
      <uni-popup-dialog ref="inputClose" mode="input" :title="popupTitle" v-model="popupValue" placeholder="请输入内容"
        @confirm="dialogInputConfirm"></uni-popup-dialog>
    </uni-popup>


    <!-- 修改头像弹窗 -->
    <uni-popup ref="editAvatarPopup" type="center" background-color="#fff">
      <view class="edit-avatar-popup">s
        <view class="upload-container">
          <image class="avatar" :src="editAvatarUrl" mode="aspectFill"></image>
          <button @tap="handleChooseImage">选择图片</button>
          <button @tap="handleSubmit">确认</button>
        </view>
      </view>
    </uni-popup>

    <!-- 注销账号弹窗 -->
    <uni-popup ref="delPopup" type="dialog">
      <uni-popup-dialog type="info" title="确认注销账号吗？" @confirm="confirmDeleteAccount"
        :duration="2000"></uni-popup-dialog>
    </uni-popup>

  </view>
</template>

<script setup>
  import {
    onLoad,
    onShow
  } from '@dcloudio/uni-app';
  import {
    ref,
    getCurrentInstance
  } from 'vue';
  import http from '../../utils/http';

  const user = ref({
    avatar: '',
    nickname: '',
    email: ''
  });


  const {
    proxy
  } = getCurrentInstance()
  const editPopup = ref(null)
  const popupEditType = ref('') // 弹窗编辑类型
  const popupTitle = ref('')
  const popupValue = ref('请输入')
  const editAvatarPopup = ref(null)
  const editAvatarUrl = ref('')
  const delPopup = ref(null)


  onLoad(() => {
    init();
  })

  const init = () => {
    // 初始化用户信息
    http.request({
      url: '/user/getUserInfo',
      method: 'GET',
    }).then((res) => {
      console.log("初始化用户信息");
      console.log(res);
      if (res.code === 1) {
        user.value = res.data;
      }
    })
  }

  function editNickname() {
    proxy.$refs.editpopup.open();
    popupEditType.value = 'nickname'
    popupTitle.value = '修改昵称'
    popupValue.value = user.value.nickname;
    console.log(user.value.nickname);
  }

  function saveNickname(nickname) {
    http.request({
      url: '/user/updateUser',
      method: 'put',
      data: {
        nickname: nickname
      }
    }).then((res) => {
      console.log(res);
      if (res.code === 1) {
        console.log(昵称修改成功);
      } else {
        console.log(昵称修改失败);
        uni.shoutToast({
          title: '昵称修改失败',
          icon: 'none',
        })
      }

    })
  }


  function editEmail() {
    proxy.$refs.editpopup.open();
    popupEditType.value = 'email'
    popupTitle.value = '修改邮箱'
    popupValue.value = user.value.email;
    console.log(user.value.email);
  }

  function saveEmail(email) {
    http.request({
      url: '/user/updateUser',
      method: 'put',
      data: {
        email: email
      }
    }).ther((res) => {
      console.log(res);
      if (res.code === 1) {
        console.log(邮箱修改成功);
      } else {
        console.log(邮箱修改失败);
        uni.shoutToast({
          title: '邮箱修改失败',
          icon: 'none',
        })
      }

    })
  }

  const dialogInputConfirm = (e) => {
    console.log(e);
    if (popupEditType.value == 'nickname') {
      saveNickname(e)
    }
    if (popupEditType.value == 'email') {
      saveEmail(e)
    }
  }


  function editAvatar() {
    editAvatarUrl.value = user.value.avatar
    console.log(editAvatarUrl.value);
    proxy.$refs.editAvatarPopup.open();
  }

  function handleChooseImage() {
    uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        console.log(JSON.stringify(res.tempFilePaths));
        console.log(user.avatar);
        editAvatarUrl.value = res.tempFilePaths[0];
      },
      fail: (err) => {
        showToast({
          title: '选择图片失败',
          icon: 'none'
        });
      }
    });
  }

  function handleSubmit() {
    // 执行图片上传操作，上传成功后提交图片地址到后端
    uni.uploadFile({
      url: import.meta.env.VITE_APP_UPLOAD_URL,
      filePath: editAvatarUrl.value,
      name: 'file',
      fileType: 'image',
      header: {
        'Authorization': uni.getStorageSync('Token')
      },
      timeout: 6000,
      success: (res) => {
        console.log("修改后的头像地址");
        console.log(res.data);
        const re = JSON.parse(res.data);
        user.value.avatar = re.data; // 获取上传后的图片地址
        // 提交图片地址到后端
        http.request({
            url: '/user/updateUser',
            method: 'PUT',
            data: {
              avatar: re.data,
            }
          }).then((res1) => {
            if (res1.code == 1) {
              console.log("修改用户信息");
              console.log(res1);
              uni.showToast({
                title: '修改成功',
                icon: 'success'
              });
              proxy.$refs.editAvatarPopup.close(); // 关闭弹窗
            } else {
              uni.showToast({
                title: '修改失败',
                icon: 'none'
              });
              proxy.$refs.editAvatarPopup.close(); // 关闭弹窗
            }
          })
          .catch((err) => {
            console.log(err);
            proxy.$refs.editAvatarPopup.close(); // 关闭弹窗
          });
      },
      fail: (err) => {
        uni.showToast({
          title: '上传失败',
          icon: 'none'
        });
      }
    });
  }

  function changePassword() {
    // 跳转到修改密码页面
    uni.navigateTo({
      url: '/pages/editPassword/editPassword'
    })
  }

  const openDelPopup = () => {
    console.log("打开注销消息弹窗");
    proxy.$refs.delPopup.open()
  }


  function confirmDeleteAccount() {
    // 在这里添加注销账号的逻辑
    console.log('确认注销账号');
    http.request({
      url: '/user/delete',
      method: 'DELETE',
    }).then((res) => {
      if (res.code == 1) {
        uni.clearStorageSync()
        uni.showToast({
          title: '注销成功',
          icon: 'success'
        })
        uni.reLaunch({
          url: '/pages/index/index'
        })
      } else {
        uni.showToast({
          title: '注销失败',
          icon: 'none'
        })
      }
    })
  }
</script>

<style scoped>
  .user-profile {
    padding: 20px;
  }

  .avatar-container {
    text-align: center;
  }

  .upload-container {
    margin-top: 20px;
    width: 100%;
  }

  .avatar {
    width: 100px;
    height: 100px;
    border-radius: 50%;
  }

  .edit-avatar-popup {
    padding: 30px 100px 30px 100px;
  }

  .avatar {
    width: 150px;
    height: 150px;
    border-radius: 50%;
  }

  .change-avatar {
    display: block;
    width: 100%;
    color: #007AFF;
    font-size: 14px;
    margin-top: 5px;
    margin-bottom: 15rpx;
    text-align: center;
  }

  button {
    display: block;
    height: 100rpx;
    margin-top: 20px;
    background-color: #007AFF;
    color: white;
    border: none;
    border-radius: 5px;
    padding: 10rpx;
    font-size: 16px;
  }

  button:hover {
    background-color: #0056b3;
  }
</style>
